package com.haikesi.filter;

import com.alibaba.fastjson.JSONObject;
import com.haikesi.api.base.User;
import com.haikesi.api.menuauthority.domain.vo.MenuAuthorityVO;
import com.haikesi.api.resource.domain.vo.ResourecesVO;
import com.haikesi.config.Constants;
import com.haikesi.config.RedisUtils;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

/**
 * @ClassName TokenFilter
 * @Author HandsomeBugs
 * @Date 2019/4/26 15:22
 * @Version 1.0
 **/
@Configuration
@Slf4j
public class AuthorityFilter extends ZuulFilter {

    @Autowired
    private RedisUtils redisUtils;

    //可以在请求被路由之前调用
    @Override
    public String filterType() {
        return "pre";
    }
    //通过int值来定义过滤器的执行顺序，越小的值越优先处理。
    @Override
    public int filterOrder() {
        return 1;
    }
    //返回一个boolean类型来判断该过滤器是否要执行，所以通过此函数可实现过滤器的开关。true:总是生效，false:不生效
    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
       //if(request.getMethod().equals("OPTIONS")){
           ctx.setSendZuulResponse(true);
           return null;
     //  }
//        //查看是否跳过token验证
//        HashMap<String, String> skipMap = new HashMap<>();
//        skipMap.put("login", "POST");
//        skipMap.put("token", "POST");
//        skipMap.put("api-docs", "GET");
//        boolean isSkipYanz = false;
//        for (String key : skipMap.keySet()) {
//            if (request.getRequestURI().indexOf(key) > 0 && skipMap.get(key).equals(request.getMethod())) {
//                isSkipYanz = true;
//                break;
//            }
//        }
//        if (isSkipYanz) {
//            ctx.setSendZuulResponse(true);
//            return null;
//        }
//
//        //校验toke 是否存在
//        String accessToken = getToken(ctx.getRequest());
//        if (StringUtils.isBlank(accessToken) || !redisUtils.hasKey(accessToken)) {
//            returnFial(ctx, 400003, "token 验证不存在");
//            return null;
//        }
//
//        //校验用户权限
//        User user= redisUtils.get(accessToken);
//        List<MenuAuthorityVO> menuAuthorityList=user.getMenuAuthorityList();
//        List<ResourecesVO>  resourecesList=user.getResourecesList();
//        if(menuAuthorityList.size()<1||resourecesList.size()<1){
//            returnFial(ctx,401000,"没有权限访问此接口");
//            return null;
//        }
//        boolean isPass=false;
//        for (ResourecesVO resourecesVO:resourecesList) {
//            if(resourecesVO.getResourcesUrl().equals(request.getRequestURI())){
//                isPass=true;
//                break;
//            }
//        }
//        if(isPass){
//            return null;
//        }
//        returnFial(ctx,401000,"没有权限访问此接口");
//        return null;
    }


    public void returnFial(RequestContext ctx, Integer code, String message) {
        ctx.setSendZuulResponse(false);
        ctx.setResponseStatusCode(401);
        ctx.getResponse().setContentType("application/json;charset=UTF-8");
        JSONObject object = new JSONObject();
        object.put("code", code);
        object.put("message", message);
        object.put("currentTimeMillis", System.currentTimeMillis());
        ctx.setResponseBody(object.toJSONString());
    }

    private String getToken(HttpServletRequest request) {
        String token = request.getParameter(Constants.TOKEN_PARAM_NAME);
        if (token == null || token.length() == 0) {
            if (request.getCookies() == null) {
                return token;
            }
            for (Cookie cookie : request.getCookies()) {
                if (cookie.getName().equalsIgnoreCase(Constants.TOKEN_PARAM_NAME)) {
                    token = cookie.getValue();
                }
            }
        }
        return token;
    }
}
